﻿#ifndef TCPSERVER_H
#define TCPSERVER_H

#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include "ComCommon.h"

class TcpServer : public QObject
{
    Q_OBJECT
public:
    explicit TcpServer(const QString& name = "", QObject *parent = nullptr);
    virtual ~TcpServer(){}
    static QMap<ComState, QString> mapServerStateLabel;

    void setConfig(const TcpComConfig& config);
    TcpComConfig getConfig() const {return mConfig;}

signals:
    void sigMsg(const QString &msg);
    void sigReceiveData(const QByteArray& data);
    void sigStateChanged(ComState state);
    void sigClientListIpChanged(QStringList listIp);

public slots:
    virtual void onInit();
    virtual void onQuit();
    void onWrite(const QString& data);
    void onWrite(const QByteArray& data);//发送数据
    void onConfigChanged(const TcpComConfig &p);

protected:
    void setState(const ComState& state);
    virtual void writeData(const QByteArray& data);
    virtual void disconnect();
    virtual void onReadyRead(QTcpSocket* socket);
    virtual void processData(QTcpSocket* socket, const QByteArray& data);
    virtual void onClientConnected();
public:
    TcpComConfig mConfig;
protected:
    ComState mState = CS_Invalid;
    //server用于监听端口，获取新的tcp连接的描述符
    QScopedPointer<QTcpServer> mServer;
    //存储已连接的socket对象
    QList<QTcpSocket*> mClientList;
    QStringList mClientListIpPort;
};

#endif // TCPSERVER_H
